﻿Imports System.Data
Imports ADOEntity
Imports System.IO

Partial Class Administrator_AMLWATCHLIST
    Inherits Web.UI.BasePage

    Private Const PathTextReadPathShare As String = "\\lib\\Data\\Folder_Share.txt"
    Private Const PathTextReadPathWatchList As String = "\\lib\\Data\\NameTaskWatchList.txt"
    Private Const pathSanctionListOnServer As String = "\\Sanction_list\\"
    Private Const pathSanctionListLogOnServer As String = "\\Sanction_list_log\\"
    Private Const pathSanctionListBackOnServer As String = "\\sanction_list_back\\"
    Private Const PathFileFloderBatch As String = "\\Sanction_List_Batch\\RunTask.txt"
    Private Const PathFileFloderBatchTest As String = "\\Sanction_List_Batch\\RunSanctionList.bat"
    Dim pathDriveOnServer As String = ""

    Dim amlWatchlistEntity As New amlWatchListEntities
    Dim SanctionEntity As New SanctionEntities

    Dim dsAmlWatchList As New DataSet
    Dim clsQuery As New clsDatabase
    Dim clsDataTable As New clsLINQToDataTable
    Dim intBeforeItemIndex As Integer
    Dim clsSessionMenuRight As clsSessionMenuRight

#Region " Even Page "
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
        btnSearch.Text = Resources.resButton.btnSearch
        btnPrint.Text = Resources.resButton.btnPrint

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            If (Not IsPostBack) Then
                LoadDataToDropdown()
                CreateControlMP()
                ' setDefaultSearch()
                setUserRightButton()
            Else
                dsAmlWatchList = Session("dsTblMaster")
                grdAmlWatchList.DataSource = dsAmlWatchList.Tables("AMLWATCHLIST")
                grdAmlWatchList.DataBind()
            End If
        Catch ex As Exception

        End Try

    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dsAmlWatchList
    End Sub

#End Region


#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "Sanction > รายงานลูกค้าที่ติดความเสี่ยงใน Sanction List"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        IsDataBind()
        clearGvIndex()
        SaveLog(1)
    End Sub

#End Region

#Region "Even GridView"

    Protected Sub grdAmlWatchList_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdAmlWatchList.PageIndexChanging
        grdAmlWatchList.PageIndex = e.NewPageIndex
        clearGvIndex()
        DataBind()
    End Sub

    Protected Sub grdAmlWatchList_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdAmlWatchList.Sorting
        Dim dt = TryCast(dsAmlWatchList.Tables("AMLWATCHLIST"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            grdAmlWatchList.DataSource = dsAmlWatchList.Tables("AMLWATCHLIST")
            grdAmlWatchList.DataBind()
            clearGvIndex()
        End If
    End Sub

    Protected Sub grdAmlWatchList_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdAmlWatchList.RowDataBound
        'convertDate = New clsDateFormat
        'If (e.Row.RowType.ToString = "DataRow") Then
        '    If Not (e.Row.Cells(5).Text = Nothing) Then
        '        Dim dteDateLogin As Date = e.Row.Cells(5).Text
        '        Dim strDate As String = ""
        '        strDate = convertDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.Th, strDateIsChk:=dteDateLogin.ToShortDateString)
        '        strDate = strDate & " " & dteDateLogin.ToLongTimeString
        '        e.Row.Cells(5).Text = strDate

        '    End If

        'End If

        If e.Row.RowType = DataControlRowType.Header Then
            Dim HeaderGrid As GridView = DirectCast(sender, GridView)
            Dim HeaderGridRow As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
            Dim HeaderCell As New TableCell()
            HeaderCell.Text = "CUSTOMER"
            HeaderCell.ColumnSpan = 4
            HeaderGridRow.Cells.Add(HeaderCell)

            HeaderCell = New TableCell()
            HeaderCell.Text = "SANCTION"
            HeaderCell.ColumnSpan = 6
            HeaderGridRow.Cells.Add(HeaderCell)


            grdAmlWatchList.Controls(0).Controls.AddAt(0, HeaderGridRow)
        End If

    End Sub

#End Region

#Region " Function"
    Private Sub setUserRightButton()

        'Dim col As New Collection
        'col.Add(btnSearch, statusbtn.Query.ToString)
        'setBtnToUserRight(col, strMenuCode, clsSessionMenuRight.getDsMenuRight)

    End Sub

    Private Sub LoadDataToDropdown()

         Try
            Dim clsDropDown As New clsMasterDropDown
            clsDropDown.setSource(ddlListType)
            clsDropDown = Nothing
        Catch ex As Exception
            WriteError(ex, "loadDataToDropDown", "SanctionHistory")
            Throw ex
        End Try

    End Sub

    'Public Sub setDefaultSearch()
    '    clsFormatDate = New clsDateFormat
    '    txtStartDate.Text = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.Th, dteDateIsChk:=Date.Now)
    '    txtEndDate.Text = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.Th, dteDateIsChk:=Date.Now)
    '    '  rdolType.SelectedIndex = 0
    '    chkSearch.Checked = True
    '    chkAdd.Checked = True
    '    chkEdit.Checked = True
    '    chkPrint.Checked = True

    'End Sub

    Private Sub clearGvIndex()
        grdAmlWatchList.SelectedIndex = -1
        '  btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()
        Try

            Dim clsFormatDate As New clsDateFormat

            If dsAmlWatchList.Tables.Contains("AMLWATCHLIST") Then
                dsAmlWatchList.Tables.Clear()
            End If

            'Dim qryAmlWatchList = From tblWatchList In amlWatchlistEntity.AMLWATCHLIST
            '                      Order By tblWatchList.UNIQUEID Ascending, tblWatchList.THFIRSTNAME Ascending, tblWatchList.THLASTNAME Ascending
            '                  Select tblWatchList.CUSTCODE, tblWatchList.DATEPROCESS, tblWatchList.LASTUPDATELIST, tblWatchList.CUSTTYPE, _
            '                  tblWatchList.THFIRSTNAME, tblWatchList.THMIDNAME, tblWatchList.THLASTNAME, tblWatchList.ENFIRSTNAME, _
            '                  tblWatchList.ENMIDNAME, tblWatchList.ENLASTNAME, tblWatchList.LISTTYPE, tblWatchList.RISKLEVEL, tblWatchList.UNIQUEID

            Dim strQryAmlWatchList = "select * from KYCADMIN.Amlwatchlist2 a"



            'If Not (ddlCusType.SelectedValue = "0") Then
            '    qryAmlWatchList = qryAmlWatchList.Where(Function(tblWatch) tblWatch.CUSTTYPE = ddlCusType.SelectedValue)
            'End If
            If Not (ddlListType.SelectedIndex = 0) Then
                'qryAmlWatchList = qryAmlWatchList.Where(Function(tblWatch) tblWatch.LISTTYPE = ddlListType.SelectedValue)
                strQryAmlWatchList += " where a.listtype = '" & ddlListType.SelectedValue & "'"
            End If

            'dsAmlWatchList.Tables.Add(clsDataTable.LINQToDataTable(qryAmlWatchList, "AMLWATCHLIST").Copy)
            Dim dtAmlWatchList2 = clsQuery.QueryDataTable(strQryAmlWatchList)
            dtAmlWatchList2.TableName = "AMLWATCHLIST"
            dsAmlWatchList.Tables.Add(dtAmlWatchList2.Copy)
            If (dtAmlWatchList2.Rows.Count = 0) Then
                lblTotal.Text = ""
                lblMsg.Visible = True
            Else
                lblMsg.Visible = False
                lblTotal.Text = "จำนวนรายการทั้งหมด " + dtAmlWatchList2.Rows.Count.ToString + " รายการ "
            End If

            grdAmlWatchList.DataSource = dsAmlWatchList.Tables("AMLWATCHLIST")
            grdAmlWatchList.DataBind()

            clsDataTable = Nothing
        Catch ex As Exception
            Throw ex
            WriteError(ex, "LoadDataToDropdown", "IsDataBind")
        End Try
    End Sub



    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

#End Region

    Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click

        Dim param As String

        param = "{ 'rptType' : '302'," _
                & " 'ListType' : '" & ddlListType.SelectedValue & "/" & ddlListType.SelectedItem.Text & "'}"


        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType, "key", "OpenWindowWithPost('../Form/frmPrintRptMaster.aspx','width=730,height=345,left=100,top=100,resizable=yes,scrollbars=yes','Report', " + param + ");", True)
        SaveLog(2)
    End Sub

    Protected Sub btnCheckCustomer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheckCustomer.Click
        Try
            Dim clsAMLWatchlist As New clsAMLWacthList
            Dim res = clsAMLWatchlist.matchSanction100()

            ScriptManager.RegisterStartupScript(Me, _
                                                                               Me.GetType(), _
                                                   "clientScript", _
                                                   "alert('" & "ระบบกำลังประมวลผล กรุณากลับเข้ามาดูใหม่อีกครั้ง" & "')", _
                                                   True)
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, _
                                                         Me.GetType(), _
                                                         "clientScript", _
                                                         "alert('" + ex.Message.Trim + "')", _
                                                         True)
        End Try


        'Try
        '    pathDriveOnServer = readfile(System.Web.HttpContext.Current.Server.MapPath("~") & PathTextReadPathShare)

        '    WriteBatFile(readfile(System.Web.HttpContext.Current.Server.MapPath("~") & PathTextReadPathWatchList))

        '    If RunBatchFile() Then
        '        System.Threading.Thread.Sleep(10000)
        '        WriteBatFile("")
        '    Else
        '        System.Threading.Thread.Sleep(10000)
        '        WriteBatFile("")
        '    End If
        '    ScriptManager.RegisterStartupScript(Me, _
        '                                                                       Me.GetType(), _
        '                                           "clientScript", _
        '                                           "alert('" & "ระบบกำลังประมวลผล กรุณากลับเข้ามาดูใหม่อีกครั้ง" & "')", _
        '                                           True)
        'Catch ex As Exception
        '    ScriptManager.RegisterStartupScript(Me, _
        '                                                 Me.GetType(), _
        '                                                 "clientScript", _
        '                                                 "alert('" + ex.Message.Trim + "')", _
        '                                                 True)
        'End Try

    End Sub


    Public Sub checkbox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) 'Handles checkbox.CheckedChanged
        'Dim box As CheckBox = DirectCast(sender, CheckBox)

        'If box.Checked = True Then
        '    MsgBox("checked!")
        'Else
        '    MsgBox("unchecked!")
        'End If
        'Dim chkSelect As CheckBox = DirectCast(sender, CheckBox)
        'Dim row As GridViewRow = DirectCast(chkSelect.NamingContainer, GridViewRow)
        'Dim hdnCheck As HiddenField = DirectCast(row.Cells(0).FindControl("hiddenField1"), HiddenField)

        'For rowIndex As Integer = 0 To grdList.Rows.Count - 1
        '    If hdnCheck.Value.Equals(grdList.Rows(rowIndex).Cells(1).Text) Then
        '        Dim checkBox = DirectCast(grdList.Rows(rowIndex).Cells(0).FindControl("chkList"), CheckBox)
        '        checkBox.Checked = chkSelect.Checked
        '    End If
        'Next

    End Sub


    Private Function RunBatchFile() As Boolean
        Dim blnComple As Boolean = False
        Dim testtext As String = ""
        Try
            Dim psi As New System.Diagnostics.ProcessStartInfo("cmd.exe")
            psi.UseShellExecute = False
            psi.RedirectStandardInput = True
            psi.RedirectStandardOutput = True
            psi.RedirectStandardError = True
            psi.WorkingDirectory = pathDriveOnServer & "\\Sanction_List_Batch\\"
            'DECLARE PROCESS

            Dim proc As System.Diagnostics.Process
            proc = System.Diagnostics.Process.Start(psi)
            'PATH OPENED AS TEXT BY STREAM READER

            ''INPUT
            Dim sin As System.IO.StreamWriter
            sin = proc.StandardInput
            ''COMMAND TO CMD
            sin.WriteLine(readfile(pathDriveOnServer & PathFileFloderBatch))
            System.Threading.Thread.Sleep(5000)
            sin.WriteLine("EXIT")
            proc.Close()

            sin.Close()

            blnComple = True
        Catch ex As Exception

            WriteError(ex, "RunBatchFile", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด RunBatchFile ")
            blnComple = False
        End Try
        Return blnComple
    End Function

    Private Sub WriteBatFile(ByVal strNameFileBat As String)
        Try

            Dim strText As String = ""
            Dim StreamReader1 As System.IO.StreamReader = System.IO.File.OpenText(pathDriveOnServer & PathFileFloderBatchTest)
            strText = StreamReader1.ReadToEnd()
            StreamReader1.Close()

            Dim intText As Integer = 0
            intText = strText.Length

            'ScriptManager.RegisterStartupScript(Me, _
            '                                                     Me.GetType(), _
            '                                                     "clientScript", _
            '                                                    "alert('" + strText + "')", _
            '                                                     True)

            Dim strTextReplace As String = strText.Replace(strText.Substring(strText.IndexOf("/tn"), strText.Length - strText.IndexOf("/tn")), "/tn " & strNameFileBat)

          

            Dim StreamWriter1 As System.IO.StreamWriter = New System.IO.StreamWriter(pathDriveOnServer & PathFileFloderBatchTest)
            StreamWriter1.WriteLine(strTextReplace)
            StreamWriter1.Close()

        Catch ex As Exception
            WriteError(ex, "WriteBatFile", "frmImportData")
            Throw New Exception("เกินข้อผิดพลาดการเขียนไฟล์ " & ex.Message)

        End Try


    End Sub

    Private Function readfile(ByVal FileFullPath As String) As String
        Dim strMsg As String = ""
        Try
            Dim srd As StreamReader = New System.IO.StreamReader(FileFullPath)
            strMsg = srd.ReadToEnd()
            srd.Close()
        Catch ex As Exception
            WriteError(ex, "readfile", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด readfile ")
        End Try
        Return strMsg
    End Function

    Private Sub SaveLog(ByVal index As Integer)
        Try
            clsSessionMenuRight = Session("ClsMenuRight")
            Dim program As String = "M73"
            Dim programName As String = " Sanction > รายงานลูกค้าที่ติดความเสี่ยงใน Sanction List"

            Dim desc As String = ""
            If index = 1 Then
                desc = "ค้นหา" + programName
            ElseIf index = 2 Then
                desc = "พิมพ์" + programName
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, index, desc, program)


            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

End Class
